<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="测试名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="testName">
              <a-input v-model="model.testName" placeholder="请输入测试名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="创建人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="tester">
              <a-input v-model="model.tester" placeholder="请输入创建人员"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="工程描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="testDescription">
              <a-input v-model="model.testDescription" placeholder="请输入工程描述"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-model-item label="关联用例" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userCaseIds">
              <a-tree
                v-model="model.userCaseIds"
                checkable
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :selected-keys="selectedKeys"
                :replaceFields="replaceFields"
                :tree-data="options"
                @expand="onExpand"
              />
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-model-item label="产品建号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="equipName">
              <a-input v-model="model.equipName" placeholder="请输入产品建号"></a-input>
            </a-form-model-item>
          </a-col>
          <!-- 硬件资源配置表格 -->
          <a-col :span="24">
            <a-form-model-item label="硬件资源配置" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div class="hardware-resource-table">
                <!-- 表格操作区域 -->
                <div class="table-operator" style="margin-bottom: 16px;">
                  <a-button type="primary" icon="plus" @click="handleAddHardware">新增硬件</a-button>
                </div>

                <!-- 硬件资源配置表格 -->
                <a-table
                  size="middle"
                  bordered
                  rowKey="id"
                  :columns="hardwareColumns"
                  :dataSource="model.hardWareList"
                  :pagination="false"
                  class="j-table-force-nowrap"
                >
                  <!-- 名称列 -->
                  <template slot="hardWareDesc" slot-scope="text, record, index">
                    <a-input
                      v-if="record.editable"
                      v-model="record.hardWareDesc"
                      placeholder="请输入描述"
                      @blur="handleSave(record, index)"
                    />
                    <span v-else>{{ text || '--' }}</span>
                  </template>

                  <!-- 状态列 -->
                  <template slot="hardWareName" slot-scope="text, record, index">
                    <j-dict-select-tag
                      v-if="record.editable"
                      v-model="record.hardWareName"
                      placeholder="请选择新增类型"
                      dict-code="hardname"
                      @change="handleChangeHard"
                    />
                    <span v-else>
                      {{ record.hardWareName }}
                    </span>
                  </template>

                  <!-- 操作列 -->
                  <template slot="action" slot-scope="text, record, index">
                    <a-button v-if="record.editable" type="link" size="small" @click="handleSave(record, index)">
                      保存
                    </a-button>
                    <a-button v-else type="link" size="small" @click="handleEdit(record, index)">
                      编辑
                    </a-button>

                    <a-divider type="vertical" />

                    <a-popconfirm
                      title="确定要删除这条硬件配置吗？"
                      @confirm="handleDelete(index)"
                      okText="确定"
                      cancelText="取消"
                    >
                      <a-button type="link" size="small" danger>删除</a-button>
                    </a-popconfirm>
                  </template>
                </a-table>

                <!-- 空状态提示 -->
                <!-- <div v-if="!model.hardWareList || model.hardWareList.length === 0" class="empty-table">
                  <a-empty description="暂无硬件资源配置" />
                </div> -->
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'EngineeringManagementForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      type: 0,
      dataTree: [],
      replaceFields: {
        title: 'label',
        key: 'value',
        children: 'children'
      },
      model: {
        hardWareList: [] // 初始化硬件资源配置数组
      },
      // 硬件资源配置表格列定义
      hardwareColumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '硬件名称',
          dataIndex: 'hardWareName',
          key: 'hardWareName',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'hardWareName' }
        },
        {
          title: '描述',
          dataIndex: 'hardWareDesc',
          key: 'hardWareDesc',
          align: 'center',
          scopedSlots: { customRender: 'hardWareDesc' }
        },

        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 150,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/engineeringManagement/add',
        edit: '/engineeringManagement/edit',
        queryById: '/engineeringManagement/queryById',
        treelist: '/testUserCase/queryAllCase'
      },
      expandedKeys: ['0-0-0', '0-0-1'],
      autoExpandParent: true,
      checkedKeys: ['0-0-0'],
      selectedKeys: []
    }
  },

  watch: {
    checkedKeys(val) {
      console.log('onCheck', val)
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },

    options() {
      // 1. 去掉 purpose === 0 的节点
      const validRoots = this.dataTree

      // 2. 仅保留两层
      return validRoots.map(node => ({
        value: node.id,
        label: node.caseName,
        yml: node.fileYml,
        // 如果还有子节点，也只放一层
        children: (node.children || [])
          .filter(c => c.purpose !== 0) // 如子节点也要过滤
          .map(c => ({
            value: c.id,
            label: c.caseName,
            yml: c.fileYml
            // 不再继续嵌套 children，级联到此为止
          }))
      }))
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    // 初始化硬件资源配置
    this.initHardwareResources()
  },
  methods: {
    handleChangeHard() {},
    /* 初始化硬件资源配置 */
    initHardwareResources() {
      if (!this.model.hardWareList) {
        this.$set(this.model, 'hardWareList', [])
      }
    },

    /* 新增硬件配置 */
    handleAddHardware() {
      const newHardware = {
        id: Date.now() + Math.random(), // 生成唯一ID
        hardWareDesc: '',
        hardWareName: '',
        editable: true // 新增时默认可编辑
      }

      this.model.hardWareList.push(newHardware)
      console.log('新增硬件配置:', newHardware)
    },

    /* 编辑硬件配置 */
    /* 编辑硬件配置 */
    handleEdit(record, index) {
      // 先取消其他所有项的编辑状态
      this.model.hardWareList.forEach((item, i) => {
        if (i !== index && item.editable) {
          this.$set(this.model.hardWareList[i], 'editable', false)
        }
      })

      // 设置当前项为编辑状态
      this.$set(this.model.hardWareList[index], 'editable', true)
    },
    /* 保存硬件配置 */
    handleSave(record, index) {
      // 验证必填字段
      if (!record.hardWareDesc || record.hardWareDesc.trim() === '') {
        this.$message.warning('请输入描述')
        return
      }

      if (!record.hardWareName) {
        this.$message.warning('请选择硬件')
        return
      }

      // 立即退出编辑模式
      this.$set(this.model.hardWareList[index], 'editable', false)

      // 去前后空格
      this.model.hardWareList[index].hardWareDesc = record.hardWareDesc.trim()

      // this.$message.success('保存成功')
      console.log('保存硬件配置:', record)
    },

    /* 删除硬件配置 */
    handleDelete(index) {
      this.model.hardWareList.splice(index, 1)
      this.$message.success('删除成功')
    },

    /* 获取状态颜色 */
    getStatusColor(status) {
      const colorMap = {
        normal: 'green',
        warning: 'orange',
        error: 'red',
        offline: 'gray'
      }
      return colorMap[status] || 'default'
    },

    /* 获取状态文本 */
    getStatusText(status) {
      const textMap = {
        normal: '正常',
        warning: '警告',
        error: '故障',
        offline: '离线'
      }
      return textMap[status] || '未知'
    },

    /* 验证硬件资源配置 */
    validateHardwareResources(rule, value, callback) {
      if (!value || value.length === 0) {
        callback()
        return
      }

      // // 检查是否有重复的硬件名称
      // const names = value
      //   .map(function(item) {
      //     return item && item.hardWareDesc ? item.hardWareDesc.trim() : ''
      //   })
      //   .filter(Boolean)
      // const uniqueNames = new Set(names)

      // if (names.length !== uniqueNames.size) {
      //   callback(new Error('硬件名称不能重复'))
      //   return
      // }

      // 检查是否有未保存的编辑项
      const hasUnsaved = value.some(item => item.editable)
      if (hasUnsaved) {
        callback(new Error('请先保存所有编辑中的硬件配置'))
        return
      }

      callback()
    },
    /* 1. 唯一对外入口 */
    selectDirectory() {
      // 如果以后想扩展 Electron，可在这里加分支
      this._openNativeDirectoryPicker()
    },

    /* 2. 浏览器原生目录选择器 */
    _openNativeDirectoryPicker() {
      const input = document.createElement('input')
      input.type = 'file'
      input.webkitdirectory = true // 关键：允许选目录
      input.multiple = false
      input.style.display = 'none'

      input.onchange = e => {
        const files = e.target.files
        if (!files || !files.length) return

        // webkitRelativePath 形如  "parent/child/file.txt"
        const fullPath = files[0].webkitRelativePath
        const dirPath = fullPath.substring(0, fullPath.lastIndexOf('/'))

        // 回填
        this.model.fileDir = dirPath
        this.$message.success(`已选择目录：${dirPath}`)
      }

      document.body.appendChild(input)
      input.click()
      document.body.removeChild(input)
    },

    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
      console.log(this.model.userCaseIds, 'selectedKeys')
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys)
      this.checkedKeys = checkedKeys
    },
    onSelect(selectedKeys, info) {
      console.log('onSelect', info)
      this.selectedKeys = selectedKeys
    },
    getList() {
      getAction(this.url.treelist, {}).then(res => {
        if (res.success) {
          this.dataTree = res.result[0].children
        } else {
          console.error('getDictItems error: : ', res)
          this.dictOptions = []
        }
      })
    },
    changeUserCaseId(value, selectedOptions) {
      console.log(value, selectedOptions)
      this.model.userCaseIds = selectedOptions[1].yml
    },
    add() {
      this.edit(this.modelDefault, 2)
    },
    edit(record, type) {
      this.type = type
      this.getList()
      this.model = Object.assign({}, record)
      // 确保硬件资源配置数组存在
      if (!this.model.hardWareList) {
        this.$set(this.model, 'hardWareList', [])
      }

      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          // 提交前检查是否有未保存的编辑项
          // 提交前检查是否有未保存的编辑项
          var hasUnsaved =
            this.model.hardWareList &&
            this.model.hardWareList.some(function(item) {
              return item.editable
            })
          if (hasUnsaved) {
            that.$message.warning('请先保存所有编辑中的硬件配置')
            return
          }

          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          httpAction(httpurl, this.model, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    }
  }
}
</script>

<style scoped>
/* 可选：添加一些样式美化 */
.ant-input-group-compact {
  display: flex;
}

.ant-input-group-compact .ant-input {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.ant-input-group-compact .ant-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}
/* 可选：添加一些样式美化 */
.ant-input-group-compact {
  display: flex;
}

.ant-input-group-compact .ant-input {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.ant-input-group-compact .ant-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

/* 硬件资源配置表格样式 */
.hardware-resource-table {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background: #fafafa;
}

.table-operator {
  display: flex;
  justify-content: flex-start;
}

.empty-table {
  padding: 40px 0;
  text-align: center;
  background: #fff;
  border-radius: 4px;
}

/* 表格行样式 */
.j-table-force-nowrap {
  background: #fff;
}

/* 编辑状态下的输入框样式 */
.ant-table-tbody .ant-input,
.ant-table-tbody .ant-select {
  width: 100%;
}
</style>
